package com.mogu.biguser.controller;


import com.mogu.biguser.common.constant.AuthConst;
import com.mogu.biguser.dao.base_sys.SysUserMapper;
import com.mogu.biguser.domain.base_sys.SysUser;
import com.mogu.biguser.shiro.ShiroKit;
import com.mogu.biguser.web.api.model.BaseResponse;
import com.mogu.biguser.web.api.model.LoginParam;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Decoder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * Created with IntelliJ IDEA
 *
 * @Author yuanhaoyue swithaoy@gmail.com
 * @Description 登陆 Controller
 * @Date 2018-04-03
 * @Time 22:28
 */

@RestController
public class LoginController {



    @Resource
    private SysUserMapper sysUserMapper;

    @RequestMapping(value = "/notLogin", method = RequestMethod.GET)
    public BaseResponse<Object> notLogin() {
        return  new BaseResponse<Object>(true, "您尚未登陆", "您尚未登陆");
    }

    @RequestMapping(value = "/notRole", method = RequestMethod.GET)
    public  BaseResponse<Object> notRole() {
        return  new BaseResponse<Object>(true, "您没有权限！", "您没有权限！");
    }

    @RequestMapping(value = "/", method = RequestMethod.GET)

    public  BaseResponse<Object> index() {
        return  new BaseResponse<Object>(true, "index！", "您没有权限！");
    }

    @RequestMapping(value = "/out", method = RequestMethod.GET)
    public  BaseResponse<Object> logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return  new BaseResponse<Object>(true, "成功注销！", "成功注销！");
    }
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public BaseResponse<Object> login(HttpServletRequest req, HttpServletResponse res)throws IOException {

        HttpSession session = req.getSession();
        String token2 = (String) session.getAttribute(AuthConst.TOKEN); //获取单点登录储存的token,里面包含了用户名和密码用于注册
        BASE64Decoder decoder = new BASE64Decoder();
        String username = token2.split("-")[0].split("_")[0];
        String password = token2.split("-")[0].split("_")[1];
        String decode = new String(decoder.decodeBuffer(password));

        Subject subject = ShiroKit.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, decode);
        subject.login(token);
//根据权限，指定返回数据
        String role = sysUserMapper.getRole(username);
         String  appid=token2;
        String sysUserName = (String) ShiroKit.getSession().getAttribute("SysUserName");
      SysUser user=  (SysUser)ShiroKit.getSession().getAttribute("SysUser");
        return new BaseResponse<Object>(true, "登录成功", new LoginParam(sysUserName,appid,appid,user.getUserhost()+""));

    }
    public  String isRole(String Name){
        SysUser user = sysUserMapper.selectByUserName( Name);
        List<String> permsList = null;
        int userId =Integer.valueOf(user.getUserId()+"");

        String role = "";
        permsList = sysUserMapper.queryAllPerms(userId,28);  //不是管理员则是获取当前系统的菜单权限， 数字2则是该系统的数字标识，在表sys_menu的basesysnum字段可看到

        for(String perms : permsList){

            if("order:deal:list".equals(perms)){
                role="2";
                return role;
            }
           else if("order:check:list".equals(perms)){
                role="3";
                return role;
            }
            else {
                role="1";

            }

        }
        return role;
    }
    /*@RequestMapping(value = "/login/{redUrl}", method = RequestMethod.GET)
    public void login(HttpServletRequest req, HttpServletResponse res,@PathVariable("redUrl")String redUrl)throws IOException {

        HttpSession session = req.getSession();
        String token2 = (String) session.getAttribute(AuthConst.TOKEN); //获取单点登录储存的token,里面包含了用户名和密码用于注册
        BASE64Decoder decoder = new BASE64Decoder();
        String username = token2.split("-")[0].split("_")[0];
        String password = token2.split("-")[0].split("_")[1];
        String decode = new String(decoder.decodeBuffer(password));

        Subject subject = ShiroKit.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, decode);
        subject.login(token);
//根据权限，指定返回数据
        String role = sysUserMapper.getRole(username);
        String  appid=token2;
       String url= URLDecoder.decode(redUrl,"UTF-8");
        req.getParameter("token");

       res.sendRedirect(url);
    }
*/

 /* */
    /**
     * 登陆
     *
     * @param username 用户名
     * @param password 密码
     *//*
    @RequestMapping(value = "/loginApp", method = RequestMethod.POST)
    public BaseResponse<Object> login(HttpServletRequest req, HttpServletResponse res,@RequestHeader(name = "Content-Type", defaultValue = "application/json") String contentType, String username, String password, String tokenApp) {


               // 从SecurityUtils里边创建一个 subject
        Subject subject = SecurityUtils.getSubject();

        // 在认证提交前准备 token（令牌）
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        token.setRememberMe(true);

        // 执行认证登陆
        subject.login(token);


        tokenApp=subject.getSession().getId()+"";
        SecurityUtils.getSubject().getSession().setTimeout(-1000L);//永远不过期
        System.err.println(tokenApp);
        System.err.println(res.getHeader("x-auth-token"));
        tokenApp=res.getHeader("x-auth-token");

        if(subject.isAuthenticated()) {
            String   role=isRole(username);
            if("1".equals(role)){
                return new BaseResponse<Object>(true, "普通用户登录成功", new LoginParam(username, tokenApp,role));
            }
            if("2".equals(role)){
                return new BaseResponse<Object>(true, "维修工组员登录成功", new LoginParam(username, tokenApp,role));
            }
            if("3".equals(role)){
                return new BaseResponse<Object>(true, "组长登录成功", new LoginParam(username, tokenApp,role));
            }

        }
        return new BaseResponse<Object>(true, "登录成功", new LoginParam(username, tokenApp,""));

    }*/
}
